import { ref, watchEffect, onMounted, computed, onUnmounted } from 'vue'

type Theme = 'light' | 'dark'
type ThemeMode = 'auto' | 'manual'

export function useTheme() {
  const theme = ref<Theme>('light')
  const themeMode = ref<ThemeMode>('auto')
  const systemTheme = ref<Theme>('light')

  let mediaQuery: MediaQueryList | null = null

  /**
   * 获取系统主题偏好
   */
  const getSystemTheme = (): Theme => {
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }

  /**
   * 获取保存的主题设置
   */
  const getSavedSettings = () => {
    const savedTheme = localStorage.getItem('theme') as Theme | null
    const savedMode = localStorage.getItem('themeMode') as ThemeMode | null

    return {
      theme: savedTheme || 'light',
      mode: savedMode || 'auto'
    }
  }

  /**
   * 应用主题到DOM
   */
  const applyTheme = (t: Theme) => {
    document.documentElement.classList.remove('light', 'dark')
    document.documentElement.classList.add(t)

    // 只在手动模式下保存主题到localStorage
    if (themeMode.value === 'manual') {
      localStorage.setItem('theme', t)
    }
  }

  /**
   * 更新当前主题
   */
  const updateTheme = () => {
    if (themeMode.value === 'auto') {
      theme.value = systemTheme.value
    }
    // 手动模式下theme.value已经被设置
  }

  /**
   * 系统主题变化监听器
   */
  const handleSystemThemeChange = (e: MediaQueryListEvent) => {
    systemTheme.value = e.matches ? 'dark' : 'light'
    if (themeMode.value === 'auto') {
      updateTheme()
    }
  }

  /**
   * 切换主题模式（自动/手动）
   */
  const toggleThemeMode = () => {
    if (themeMode.value === 'auto') {
      // 切换到手动模式，保持当前主题
      themeMode.value = 'manual'
      localStorage.setItem('themeMode', 'manual')
      localStorage.setItem('theme', theme.value)
    } else {
      // 切换到自动模式，跟随系统主题
      themeMode.value = 'auto'
      localStorage.setItem('themeMode', 'auto')
      localStorage.removeItem('theme') // 清除手动设置的主题
      updateTheme()
    }
  }

  /**
   * 手动切换主题（仅在手动模式下有效）
   */
  const toggleTheme = () => {
    if (themeMode.value === 'manual') {
      theme.value = theme.value === 'light' ? 'dark' : 'light'
    }
  }

  /**
   * 设置为手动模式并切换主题
   */
  const setManualTheme = (newTheme: Theme) => {
    themeMode.value = 'manual'
    theme.value = newTheme
    localStorage.setItem('themeMode', 'manual')
    localStorage.setItem('theme', newTheme)
  }

  onMounted(() => {
    // 初始化系统主题
    systemTheme.value = getSystemTheme()

    // 获取保存的设置
    const saved = getSavedSettings()
    themeMode.value = saved.mode

    if (themeMode.value === 'auto') {
      theme.value = systemTheme.value
    } else {
      theme.value = saved.theme
    }

    // 监听系统主题变化
    mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', handleSystemThemeChange)

    applyTheme(theme.value)
  })

  onUnmounted(() => {
    // 清理监听器
    if (mediaQuery) {
      mediaQuery.removeEventListener('change', handleSystemThemeChange)
    }
  })

  watchEffect(() => {
    applyTheme(theme.value)
  })

  return {
    theme,
    themeMode,
    systemTheme,
    toggleTheme,
    toggleThemeMode,
    setManualTheme,
    isDark: computed(() => theme.value === 'dark'),
    isAuto: computed(() => themeMode.value === 'auto'),
    isManual: computed(() => themeMode.value === 'manual')
  }
}
